package com.nantai.jiafang.nantaijiafang.nt5s.Activity;

import android.app.DatePickerDialog;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.github.mikephil.charting.charts.LineChart;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nantai.jiafang.nantaijiafang.R;
import com.nantai.jiafang.nantaijiafang.nt5s.IConstant;
import com.nantai.jiafang.nantaijiafang.nt5s.bean.Chart_Item;
import com.nantai.jiafang.nantaijiafang.nt5s.bean.DynamicLineChartManager;
import com.nantai.jiafang.nantaijiafang.nt5s.bean.HomeItem;
import com.nantai.jiafang.nantaijiafang.nt5s.utils.Tools;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/10/21.
 */

public class LineChartActivity extends AppCompatActivity implements View.OnClickListener{
    private Spinner spinner;
    private ArrayList<String> homelist=new ArrayList<>();
    private LineChart lineChart1;
    private ArrayList<Float> chartdata1=new ArrayList<>();
    private ArrayList<Float> chartdata2=new ArrayList<>();
    private ArrayList<Float> chartdata3=new ArrayList<>();
    private ArrayList<String> chartweek=new ArrayList<>();
    private ArrayList<ArrayList<Float>> chartdatalist=new ArrayList<>();
    private DynamicLineChartManager dynamicLineChartManager1;
    private List<String> names = new ArrayList<>(); //折线名字集合
    private List<Integer> colour = new ArrayList<>();//折线颜色集合
    private Button button,zongshu;
    private TextView start_date,end_date;
    private int[] lines;
    private CheckBox checkBox0,checkBox1,checkBox2;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_linechart);
        spinner=(Spinner)findViewById(R.id.select_home);
        lineChart1 = (LineChart) findViewById(R.id.linechart);
        button=(Button)findViewById(R.id.computer);
        start_date=(TextView)findViewById(R.id.start_date);
        start_date.setOnClickListener(this);
        end_date=(TextView)findViewById(R.id.end_date);
        end_date.setOnClickListener(this);
        button.setOnClickListener(this);
        zongshu=(Button)findViewById(R.id.zongshu);
        zongshu.setOnClickListener(this);
        checkBox0=(CheckBox)findViewById(R.id.check0);
        checkBox0.setOnClickListener(this);
        checkBox1=(CheckBox)findViewById(R.id.check1);
        checkBox1.setOnClickListener(this);
        checkBox2=(CheckBox)findViewById(R.id.check2);
        checkBox2.setOnClickListener(this);
        initdata2();
        gethome();

    }
    @Override
    public void onClick(View v) {
        Calendar calendar = Calendar.getInstance();
        switch (v.getId()){
            case R.id.computer:
                if (Tools.isNetAvailuable(this)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    if (start_date.getText().toString().equals("开始日期")||end_date.getText().toString().equals("结束日期")){
                        Toast.makeText(this, "请选择日期", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    try {
                        Date d1 = sdf.parse(start_date.getText().toString());
                        Date d2 = sdf.parse(end_date.getText().toString());
                        if (d1.after(d2)) {
                            Tools.showToast(this, "开始日期要在结束日期之后");
                        } else if (d1.getYear()!=d2.getYear()) {
                            Tools.showToast(this, "日期间隔不能跨年");
                        } else {
                            button.setEnabled(false);
                            lineChart1.setScaleMinima(1.0f, 1.0f);
                            lineChart1.getViewPortHandler().refresh(new Matrix(), lineChart1, true);
                            dynamicLineChartManager1 = new DynamicLineChartManager(LineChartActivity.this,lineChart1, names, colour);
                            dynamicLineChartManager1.setDescription("张/周");
                            nettochart();
                        }
                    } catch (ParseException ignored) {

                    }
                    lines=new int[names.size()];
                    for (int i = 0; i < names.size(); i++) {
                        lines[i]=1;
                    }
                    checkBox0.setChecked(true);
                    checkBox1.setChecked(true);
                    checkBox2.setChecked(true);

                } else {
                    Tools.showToast(this, "当前网络不可用，请检查网络");
                }
                break;
            case R.id.start_date:
                current_start_end_date_state=1;
                DatePickerDialog dpd = new DatePickerDialog(this, Datelistener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dpd.show();
                break;
            case R.id.end_date:
                current_start_end_date_state=2;
                DatePickerDialog dpd2 = new DatePickerDialog(this, Datelistener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dpd2.show();
                break;
            case R.id.check0:
                if (lines == null) {
                    return;
                }
                lines[0]=checkBox0.isChecked() ? 1:0;
                dynamicLineChartManager1.initLineDataSet(names,lines);
                break;
            case R.id.check1:
                if (lines == null) {
                    return;
                }
                lines[1]=checkBox1.isChecked() ? 1:0;
                dynamicLineChartManager1.initLineDataSet(names,lines);
                break;
            case R.id.check2:
                if (lines == null) {
                    return;
                }
                lines[2]=checkBox2.isChecked() ? 1:0;
                dynamicLineChartManager1.initLineDataSet(names,lines);
                break;
//            case R.id.zongshu:
//                lines=new int[names.size()];
//                AlertDialog.Builder builder = new AlertDialog.Builder(this);
//                builder.setTitle("请选择");
//                builder.setMultiChoiceItems(R.array.selectchart,null, new DialogInterface.OnMultiChoiceClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
//                        if (isChecked){
//                            lines[which]=1;
//                        }else {
//                            lines[which]=0;
//                        }
//
//                    }
//
//                });
//                builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
//                {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which)
//                    {
//                        dynamicLineChartManager1.initLineDataSet(names,lines);
//                    }
//                });
//                builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
//                {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which)
//                    {
//                    }
//                });
//                builder.show();
//                break;
        }
    }
private int current_start_end_date_state=0;
    private DatePickerDialog.OnDateSetListener Datelistener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {
            String month="";
            String day="";
            if (monthOfYear<9){
                month="0"+(monthOfYear+1);
            }else {
                month=""+(monthOfYear+1);
            }
            if (dayOfMonth<10){
                day="0"+dayOfMonth;
            }else {
                day=""+dayOfMonth;
            }
            if (current_start_end_date_state == 2) {
                end_date.setText(myyear + "-" +month + "-" + day);
            } else {
                start_date.setText(myyear + "-" +month + "-" + day);
            }

        }
    };
    //屏幕方向发生改变的回调方法
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
            lineChart1.setScaleMinima(1.0f, 1.0f);
            lineChart1.getViewPortHandler().refresh(new Matrix(), lineChart1, true);
            dynamicLineChartManager1 = new DynamicLineChartManager(LineChartActivity.this,lineChart1, names, colour);
            dynamicLineChartManager1.setDescription("张/周");
            show();
        super.onConfigurationChanged(newConfig);
        Log.e("TAG", "onConfigurationChanged");
        //  setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);  //设置横屏
    }
    private void initdata2(){
        names.add("总数");
        names.add("现场");
        names.add("质量");
        //折线颜色
        colour.add(Color.RED);
        colour.add(Color.GREEN);
        colour.add(Color.BLUE);
    }
    private Float maxnumber(ArrayList<ArrayList<Float>> list){
        float max=0;
        for (int i = 0; i <list.size() ; i++) {
            for (int j = 0; j <list.get(i).size() ; j++) {
                if (max<list.get(i).get(j))
                    max=list.get(i).get(j);
            }
        }
        // Log.e("sdf", "onClick: "+String.valueOf(max) );
        return max;
    }
    private void gethome(){
        homelist.clear();
        homelist.add("请选择车间");
        String url = IConstant.URLWORKSPACE;
        StringRequest postRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Gson gson=new Gson();
                        List<HomeItem> chartdata = gson.fromJson(response, new TypeToken<List<HomeItem>>()
                        {}.getType());
                        for (HomeItem homeItem :
                                chartdata) {
                            homelist.add(homeItem.getDeptName());
                            //Toast.makeText(MainActivity.this, String.valueOf(chartitem.getWeek()), Toast.LENGTH_SHORT).show();
                        }
                        ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(LineChartActivity.this,android.R.layout.simple_spinner_dropdown_item,homelist);
                        spinner.setAdapter(arrayAdapter);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                      //  Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                        error.printStackTrace();
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<>();
                // the POST parameters:
                params.put("opType", "getOrganization");
                return params;
            }
        };
        Volley.newRequestQueue(this).add(postRequest);
    }
    private void nettochart(){

        chartdata1.clear();
        chartdata2.clear();
        chartdata3.clear();
        chartweek.clear();
        String url = IConstant.URLWORKSPACE;
        StringRequest postRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            Gson gson = new Gson();
                            List<Chart_Item> chartdata = gson.fromJson(response, new TypeToken<List<Chart_Item>>() {
                            }.getType());
                            for (Chart_Item chartitem :
                                    chartdata) {
                                //Toast.makeText(MainActivity.this, String.valueOf(chartitem.getWeek()), Toast.LENGTH_SHORT).show();
                                chartdata1.add(chartitem.getTotal());
                                chartdata2.add(chartitem.getNowCard());
                                chartdata3.add(chartitem.getQualityCard());
                                chartweek.add(String.valueOf((int)chartitem.getWeek()));
                            }
                            show();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        button.setEnabled(true);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(LineChartActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                        error.printStackTrace();
                        button.setEnabled(true);
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String>  params = new HashMap<>();
                // the POST parameters:
                params.put("opType", "getChartDiagram");
                params.put("BeginDate", start_date.getText().toString());
                params.put("OutDate", end_date.getText().toString());
                params.put("WorkShop", spinner.getSelectedItem().toString());
                return params;
            }
        };
        Volley.newRequestQueue(this).add(postRequest);

        //Toast.makeText(MainActivity.this, postRequest.getBody(), Toast.LENGTH_SHORT).show();
    }
    private void show(){
        chartdatalist.clear();
        chartdatalist.add(chartdata1);
        chartdatalist.add(chartdata2);
        chartdatalist.add(chartdata3);
        float maxx2=maxnumber(chartdatalist)+5-maxnumber(chartdatalist)%5;
        dynamicLineChartManager1.setYAxis(maxx2, 0, 10);
        dynamicLineChartManager1.addEntry(chartweek,chartdatalist);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        lineChart1=null;
        dynamicLineChartManager1=null;
    }
}
